package xyz.xpman.prisonerfitness.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import org.jetbrains.annotations.NotNull;

@SuppressWarnings("unused")
public class AppUtil {
    public static final String APP_NAME = "prisonerfitness";
    private static final String VERSION_KEY = "version";

    private static int versionCode = 0;
    private static String versionName = "";
    private static long firstInstallTime;
    private static boolean isFirstRun = false;

    private AppUtil() { }


    public static void init(@NotNull Context context) {
        initIsFirstRun(context);
        initVersionInfo(context);
    }


    public static void initVersionInfo(@NotNull Context context) {
        PackageInfo packageInfo = getPackageInfo(context);

        versionCode = packageInfo.versionCode;
        versionName = packageInfo.versionName;
        firstInstallTime = packageInfo.firstInstallTime;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();

            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }


    private static void initIsFirstRun(@NotNull Context context) {
        final String key = "is_first_run";
        final String fileName = "first_run_sp";

        SharedPreferences setting = context.getSharedPreferences(fileName, 0);

        final int version = setting.getInt(VERSION_KEY, -1);
        final boolean user_first =
                version != versionCode || setting.getBoolean(key, true);

        if (user_first) {
            // 第一次则跳转到欢迎页面
            setting.edit()
                    .putBoolean(key, false)
                    .putInt(VERSION_KEY, versionCode)
                    .apply();
            isFirstRun = true;
        } else {
            // 如果是第二次启动则直接跳转到主页面
            isFirstRun = false;
        }
    }



    public static String getName() {
        return APP_NAME;
    }

    /**
     * 获取APP当前版本信息: versionCode.versionName
     *
     * @return versionInfo
     */
    public static String getVersionInfo() {
        return versionCode + "." + versionName;
    }

    /**
     * 获取APP当前版本号
     *
     * @return version
     */
    public static int getVersionCode() {
        return versionCode;
    }

    /**
     * 获取APP当前版本名称
     *
     * @return versionName
     */
    public static String getVersionName() {
        return versionName;
    }


    public static long getFirstInstallTime() {
        return firstInstallTime;
    }


    public static boolean isFirstRun() {
        return isFirstRun;
    }

}
